import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;

public class UploadServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;
  private static final String DEFAULT_UPLOAD_DIR = "c:\\temp\\";
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    doPost(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException
  {
    try
    {
      int maxMemSize = 900000;
      long maxReqSize = 1000000000;
      String fileDir = DEFAULT_UPLOAD_DIR; // destination for uploaded images
      String tmpStr = "";
      int num = 0;

      // Create a new file upload handler
      DiskFileUpload upload = new DiskFileUpload();
      upload.setSizeThreshold(maxMemSize);
      upload.setSizeMax(maxReqSize);
      upload.setRepositoryPath(fileDir);
      List items = upload.parseRequest(request);
      Iterator iter = items.iterator();
      while (iter.hasNext())
      {
        FileItem item = (FileItem) iter.next();
        if (!item.isFormField())
        {
          if (item != null && (tmpStr = item.getName()) != null
              && tmpStr.length() > 0)
          {
            if ((num = tmpStr.lastIndexOf('\\')) > 0)
            {
              tmpStr = tmpStr.substring(num + 1, tmpStr.length());
            }
            System.out.println("Name: " + item.getName());
            String renamedFile = "test.xls";
            File uploadedFile = new File(fileDir + renamedFile);
            item.write(uploadedFile);
          }
        }
      }
    } catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}